package com.lg.concurrent.share_parameter;

/**
 * 多线程在访问同一个  共享变量是
 * 出现线程安全问题
 * <p>
 * java 利用锁解决这个问题
 */
public class ShareNum {

    static class NumThread extends Thread {
        private int num = 5;
        @Override
        public void run() {
            num--;
            System.out.println(Thread.currentThread().getName() + " 计算出Num值为： " + num);
        }
    }


    static class NumLockThread extends Thread {
        private int num = 5;

        @Override
        public void run() {
            synchronized (this) {
                num--;
                System.out.println(Thread.currentThread().getName() + " 计算出Num值为： " + num);
            }
        }
    }

    public static void main(String[] args) {
        NumThread numThread = new NumThread();
        Thread aa = new Thread(numThread, "com.lg.aa");
        Thread bb = new Thread(numThread, "bb");
        Thread cc = new Thread(numThread, "cc");
        Thread dd = new Thread(numThread, "dd");
        aa.start();
        bb.start();
        cc.start();
        dd.start();

        NumLockThread numLockThread = new NumLockThread();
        Thread aa1 = new Thread(numLockThread, "aa1");
        Thread bb1 = new Thread(numLockThread, "bb1");
        Thread cc1 = new Thread(numLockThread, "cc1");
        Thread dd1 = new Thread(numLockThread, "dd1");
        aa1.start();
        bb1.start();
        cc1.start();
        dd1.start();


    }
}
